﻿using System;
using System.Collections.Generic;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Web;
using Pyramid.Models;
using Pyramid.Security;

namespace Pyramid.Bll
{
	public class CustomerHelper : BllBase
	{
		public static CustomerHelper NewInstance
		{
			get { return new CustomerHelper(); }
		}

		public IQueryable<Customer> Query(CustomerQueryModel model, CustomPrincipal user)
		{
			var customers = Db.Customers.Where(x => x.CreateUserId == user.UserId);
			if (!string.IsNullOrWhiteSpace(model.CustomerCode))
			{
				customers = customers.Where(x => x.Code.Contains(model.CustomerCode));
			}
			if (!string.IsNullOrWhiteSpace(model.Keywords))
			{
				customers = customers.Where(x => x.FullName.Contains(model.Keywords));
			}
			if (model.CreateTimeFrom.HasValue)
			{
				customers = customers.Where(x => SqlFunctions.DateDiff("d", model.CreateTimeFrom.Value, x.CreateTime) >= 0);
			}
			if (model.CreateTimeTo.HasValue)
			{
				customers = customers.Where(x => SqlFunctions.DateDiff("d", model.CreateTimeTo.Value, x.CreateTime) <= 0);
			}
			return customers;
		}

		public Customer Single(int customerId)
		{
			return Db.Customers.Single(x => x.Id == customerId);
		}
	}
}